package com.chat.datea.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.chat.datea.R;
import com.chat.datea.adapter.SearchAdapter;
import com.chat.datea.adapter.SearchListViewAdapter;
import com.chat.datea.adapter.SearchTopGridViewAdapter;
import com.chat.datea.bean.MusicList;
import com.chat.datea.bean.SearchSongEntity;
import com.chat.datea.bean.SearchTopEntity;
import com.chat.datea.bean.SongSearch;
import com.chat.datea.ui.MainActivity;
import com.chat.datea.utils.china_for_utf_8.FormatCodeUtil;
import com.chat.datea.utils.slidedeletelistview.SlideCutListView;
import com.chat.datea.utils.volley.VolleySingleton;
import com.google.gson.Gson;

import java.util.ArrayList;

/**
 * Created by 周橹 on 15/10/28.
 */
public class SearchFragment extends Fragment implements View.OnClickListener {
    private View view;
    private String data;
    private EditText search_editText;
    private ImageView search_back, search_search;
    private ImageView search_delete;
    private RequestQueue queue;
    private GridView search_top_gridView; // 热门搜索标签GridView
    private SlideCutListView search_result_listView, search_history_listView; // 搜索结果、历史SlideCutListView
    private ArrayList<SearchSongEntity> entities;
    private LinearLayout search_linearLayout, search_linearLayout_mask;
    private ArrayList<SearchTopEntity.ResultEntity> resultEntities;
    private VolleySingleton volleySingleton;
    private SearchAdapter searchAdapter;
    private SearchListViewAdapter searchListViewAdapter;
    private SearchTopGridViewAdapter searchTopGridViewAdapter;
    private String url = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=android&version=5.6.5.0&method=baidu.ting.search.hot";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        volleySingleton = VolleySingleton.getVolleySingleton(getActivity());
        view = inflater.inflate(R.layout.search_layout, null);
        initView(view);
        getData();
        return view;
    }

    private void initView(View view) {

        search_editText = (EditText) view.findViewById(R.id.search_editText);
        search_history_listView = (SlideCutListView) view.findViewById(R.id.search_history_listView);
        search_history_listView.setRemoveListener(new SlideCutListView.RemoveListener() {

            /**
             * 滑动删除之后的回调方法
             */
            @Override
            public void removeItem(SlideCutListView.RemoveDirection direction, int position) {
                searchListViewAdapter.remove(searchListViewAdapter.getItem(position));
            }
        });
        search_result_listView = (SlideCutListView) view.findViewById(R.id.search_result_listView);
        search_result_listView.setRemoveListener(new SlideCutListView.RemoveListener() {

            /**
             * 滑动删除之后的回调方法
             */
            @Override
            public void removeItem(SlideCutListView.RemoveDirection direction, int position) {
                searchAdapter.remove(searchAdapter.getItem(position));
            }
        });

        search_history_listView = (SlideCutListView) view.findViewById(R.id.search_history_listView);
        search_top_gridView = (GridView) view.findViewById(R.id.search_top_gridView);
        search_linearLayout = (LinearLayout) view.findViewById(R.id.search_linearLayout);
        search_linearLayout_mask = (LinearLayout) view.findViewById(R.id.search_linearLayout_mask);
        search_linearLayout_mask.setVisibility(View.GONE);
        search_delete = (ImageView) view.findViewById(R.id.search_delete);
        search_back = (ImageView) view.findViewById(R.id.search_back);
        search_search = (ImageView) view.findViewById(R.id.search_search);
        search_back.setOnClickListener(this);
        search_search.setOnClickListener(this);

        queue = Volley.newRequestQueue(getActivity());
        onTextChanged();  // 调取数据变化的方法
        onTextDelete(); // 调取数据出现时点击删除的方法
    }

    private void getData() {
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(final String response) {
                Gson gson = new Gson();
                SearchTopEntity searchTopEntity = gson.fromJson(response, SearchTopEntity.class);
                resultEntities = searchTopEntity.getResult();
                searchTopGridViewAdapter = new SearchTopGridViewAdapter(getActivity(), resultEntities);
                search_top_gridView.setAdapter(searchTopGridViewAdapter);
                search_top_gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // 使EditText获取文本
                        String name = resultEntities.get(position).getWord().toString();
                        search_editText.setText(name);

//                        SharedPreferences preferences = getActivity().getSharedPreferences("searchResult", 0);
//                        SharedPreferences.Editor editor = preferences.edit();
//                        editor.putString("searchResult", name);
//                        editor.commit();

                        searchListViewAdapter = new SearchListViewAdapter(getActivity(), resultEntities);
                        search_history_listView.setAdapter(searchListViewAdapter);
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request, "SearchFragment");
    }

    // 数据变化的方法
    private void onTextChanged() {

        // 数据变化的监听
        search_editText.addTextChangedListener(new TextWatcher() {


            /**
             *文本框改变之前会执行的动作
             */
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            /**
             * 文本框改变时执行的动作
             */
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            /**
             * 文本框改变之后会执行的动作
             * 因为我们要做的是在文本框改变的同时，同时ListView的数据也相应做出改变，并且显示在界面上
             * 所以这里我们需要加上数据修改的动作
             * @param s
             */
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    search_delete.setVisibility(View.GONE);
                    search_linearLayout.setVisibility(View.VISIBLE);
                    search_linearLayout_mask.setVisibility(View.GONE);
                } else {
                    search_delete.setVisibility(View.VISIBLE);
                    search_linearLayout.setVisibility(View.GONE);
//                    search_linearLayout_mask.setVisibility(View.VISIBLE);
//                    search_result_listView.setVisibility(View.GONE);
                }

                Handler handler = new Handler();
                handler.post(eChanged);
            }
        });
    }

    /**
     * 利用线程实现UI界面更新
     */
    Runnable eChanged = new Runnable() {
        @Override
        public void run() {

            // 从search_editText组件获得数据
            data = search_editText.getText().toString();
            // 将search_editText获得的数据转码成utf-8格式的数据
            String songUrl = FormatCodeUtil.codingFormat(data);
            // 进行网址拼接
            String url = "http://tingapi.ting.baidu.com/" +
                    "v1/restserver/ting?from=android&version=5.6.5.2&method=baidu.ting.search.catalogSug&format=json&query=" + songUrl;
            Log.i("lanou", url + "");

            // 进行网络请求
            StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Gson gson = new Gson();
                    SongSearch songSearch = gson.fromJson(response, SongSearch.class);
                    // 获得数据
                    entities = songSearch.getSong();

                    // 初始化适配器
                    searchAdapter = new SearchAdapter(getActivity(), entities);

                    // 绑定适配器
                    search_result_listView.setAdapter(searchAdapter);

                    search_result_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            ArrayList<MusicList> lists = new ArrayList<>();
                            for (SearchSongEntity searchSongEntity : entities) {
                                MusicList musicList = new MusicList();
                                musicList.setName(searchSongEntity.getSongname());
                                musicList.setSinger(searchSongEntity.getArtistname());
                                musicList.setSongId(searchSongEntity.getSongid());
                                musicList.setFrom("网络");
                                lists.add(musicList);
                            }

                            MainActivity.play(lists, position);
                            Toast.makeText(getActivity(), "请稍候!音乐正在路上", Toast.LENGTH_SHORT).show();

//                            String str = getText(position).toString();
//                            String songInfo = FormatCodeUtil.codingFormat(str);
//                            String url = "http://tingapi.ting.baidu.com/" +
//                                    "v1/restserver/ting?from=android&version=5.6.5.2&method=baidu.ting.search.merge&format=json&query=" + songInfo
//                                    + "&page_no=1&page_size=50&type=-1&data_source=0&use_cluster=1";
//                            Log.i("lanou", url + "");

//                            FragmentTransaction transaction = getFragmentManager().beginTransaction();
//                            SearchResultFragment searchResultFragment = new SearchResultFragment();
//                            new ReplaceFragment(searchResultFragment, getActivity().getSupportFragmentManager(), R.id.fl_content, true, null);
//                            transaction.commit();

                        }
                    });
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

            // 添加队列
            queue.add(request);
        }
    };

    private void onTextDelete() {
        search_delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 将数据滞空
                search_editText.setText("");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_back:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.search_search:
                search_linearLayout_mask.setVisibility(View.GONE);
                break;
        }
    }
}
